<?php
namespace app\api\controller;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Db;
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;
class traceability extends common
{
    private $dbname = 'traceability';


    /**
     * 列表分页获取
     * @return string
     */
    public function getlist()
    {

        $data = input('get.');

        $where = [];
        if(!empty($data['name'])){
            $where[] = ['traceability.code
                |traceability.wdm
                ','like','%'.$data['name'].'%'];
        }

        if(!empty($data['status'])){
            $where[] = ['traceability.status','=',$data['status']];
        }else{
            $where[] = ['traceability.status','in',[0,1,2]];
        }


        $list = Db::view($this->dbname,'*')
            ->where($where)
            ->order('status asc,id desc')
            ->paginate([
                'list_rows'=> $data['limit'],
                'var_page' => 'page',
            ])->toArray();

        return re_success('获取成功',$list);
//        return re_list($list);
    }
    /**
     * 列表分页获取
     * @return string
     */
    public function getBatchList()
    {

        $data = input('get.');
        $where = [];
        $where[] = ['traceability.status','in',[0,1]];
//        $where[] = ['traceability.company_id','=',$data['company_id']];
//        $where[] = ['traceability.product_id','=',$data['product_id']];
//        $where[] = ['traceability.batch_id','=',$data['batch_id']];

        $list = Db::view($this->dbname,'*')
            ->where($where)
            ->view('product', 'name as product_name', 'product.id = traceability.product_id', 'LEFT')
            ->view('company', 'name as company_name', 'company.id = traceability.company_id', 'LEFT')
            ->view('batch', 'code as batch_code', 'batch.id = traceability.batch_id', 'LEFT')
            ->order('id asc')
            ->paginate([
                'var_page' => 'page',
                'list_rows'=> $data['limit'],
            ])->toArray();
//        foreach ($list['data'] as $k=>$v ){
//            $list['data'][$k]['code'] = $v['code'];//openssl_decrypt($v['code'], 'DES-ECB', config('app')['cache_shaf'], 0);
//        }
        return re_success('获取成功',$list);
//        return re_list($list);
    }




    /**
     * 列表分页获取
     * @return string
     */
    public function getSeleList()
    {
        $data = input('get.');
        $where = [];
        if(!empty($data['id']) ){
            $list = Db::name($this->dbname)->whereOr('id','=',$data['id'])->whereOr('name','like','%'.$data['name'].'%')->field('id,rank,status')->select()->toArray();

        }else if(!empty($data['product_id']) ){
            $list = Db::name($this->dbname)
                ->where('status',1)
                ->where('product_id',$data['product_id'])->field('id,rank,status')->select()->toArray();

        }else{
            $list = Db::name($this->dbname)->field('id,rank,status')->select()->toArray();

        }
        return re_success('获取成功',$list);
    }
    /**
     * 添加
     * @return false|string|void
     */
    public function insert()
    {
//        $data = input('post.');
//        $data['user_id'] = $this->getThisUser()['uid'];
//        //模型数据验证
        $model = new \app\api\model\Traceability();
//
//        $er = $model->add_vali($data);
//        if($er){
//            return  $er;
//        }
        $data['user_id'] = 2;
        $data['batch_id'] = null;
        $data['code'] = '230920S';
        $data['number'] = 110000;
        $data['company_id'] = null;
        $data['product_id'] = null;
        //模型写入
        $data['time'] = date('Y-m-d H:i:s');
        $new_data = [];
        $cache_shaf = config('app')['cache_shaf'];
        for($i=0;$i<$data['number'];$i++){
            $option = $data['code'].'1'.code_str_pad(8,$i+1);//code_str_pad(12,$product_id).code_str_pad(5,$company_id).'I23'.'53';
//            $code =  openssl_encrypt($option, 'DES-ECB', $cache_shaf, 0);

            $new_data[] = [
                'user_id'=>$data['user_id'],
                'time'=>$data['time'],
                'product_id'=>$data['product_id'],
                'company_id'=>$data['company_id'],
                'batch_id'=>$data['batch_id'],
                'url'=>config('app')['applet']['url'],
                'status'=>1,
                'code'=>$option,
//                'jm'=>openssl_decrypt($code, 'DES-ECB', config('app')['cache_shaf'], 0),
//                'mm'=>$option
            ];
        }

        return $model->add($new_data);
    }

    public function exlToSql(){

        $model = new \app\api\model\Traceability();
        $list = Db::view($this->dbname,'id')
            ->where('wdm','=','')//146143
            ->field('id,wdm')->select()->toArray();

        foreach ( $list as $k=>$v){
            $list[$k]['wdm'] = code_str_pad(8,$v['id']);
            Db::name($this->dbname)->where('id',$v['id'])->update(['wdm'=>code_str_pad(8,$v['id'])]);
        }
//        exit();
//        $model->startTrans();
//        try {
//
//
//            $model->saveAll($list);
//            $model->commit();
//            return re_success("添加成功");
//            // 提交事务
//        } catch (\Exception $e) {
//            // 回滚事务
//            $model->rollback();
//            return re_error($e->getMessage());
//        }
    }
    /**
     * 实现文件上传
     * @param object $file 上传的文件的对象信息
     * @param string $path 文件上传的目录
     * @return string|array 上传失败返回原因 成功返回文件的新名字数组
     */
    public function move($file, $path,$maxSize,$type)
    {

        try {
            // 判断逻辑错误
            if ($file->getSize() > $maxSize) {
                return re_error('上传文件超出了文件限制的大小'.$file->getSize().'---'.$maxSize);
                die();
            }

            // 判断文件类型
            $ext = strtolower($file->getOriginalExtension());
            if (!in_array($ext, $type, true)) {
                // 非法的文件类型
                return re_error('上传文件类型被拒绝或不符合');
                die();
            }

            $savename  = \think\facade\Filesystem::disk('public')->putFile( $this->path, $file);
            if ($savename) {
                $savename = str_replace("‘\’", '/', $savename);
                $savename = str_replace("\\", '/', $savename);
                return re_success('上传成功',['url'=>$savename,'size'=>$maxSize,'name'=>$file->getOriginalName()]);
            }else{
                // 上传失败获取错误信息
                return re_error('上传失败'.$file->getError());
                die();
            }
        } catch (\Exception $e) {
            return re_error('上传失败'.$e->getMessage() . $e->getLine());
        }
    }

    /**
     * @return void
     * 导入微点码
     */
    public function uploadXlsx(){


//        $open = '231020S100219994';
//        $end = '231020S100220000';
//        $wdm_open = '00329994';
//        $wdm_end = '00330001';
//        $list= Db::name($this->dbname)->where('wdm','=','')->where('id','<=',220000)->field('id,wdm')->select()->toArray();
//        foreach ($list as $k=>$v){
//            $list[$k]['wdm'] = code_str_pad(8,$v['id']);
//        }
//        return json_encode($list);
//        dump($list);
//        exit();

//    use PhpOffice\PhpSpreadsheet\IOFactory;

//        // 获取表单上传文件 例如上传了001.jpg
//        $file = request()->file('file');
//        // 上传到本地服务器
//        $savename = \think\facade\Filesystem::putFile( 'public', $file);
//

        $filename = 'uploads/1.xlsx';


// 通过IOFactory加载文件
        $spreadsheet = IOFactory::load($filename);

// 获取第一个工作表
        $worksheet = $spreadsheet->getActiveSheet();

// 获取行数和列数
        $rows = $worksheet->getHighestRow();
        $columns = $worksheet->getHighestColumn();

// 循环读取数据
        $arr = [];
        for ($row = 2; $row <= $rows; $row++) {
            $arr_1 = [];
            for ($column = 'A'; $column <= $columns; $column++) {
                $cellValue = $worksheet->getCell($column . $row)->getValue();
                $arr_1[] = $cellValue;
//                echo $cellValue . "\t";
            }
            $arr[] = $arr_1;
//            echo "\n";
        }

        $list= Db::name($this->dbname)->where('wdm','=','')->field('id,wdm,url,code')->select()->toArray();

        foreach ($list as $k=>$v){
            $url =  $v['url'].'?c='.openssl_encrypt($v['code'], 'DES-ECB', config('app')['cache_shaf'], 0);
            foreach ($arr as $kk=>$vv){
                if($url == $vv[0]){

                    $er =  Db::name($this->dbname)->where('id',$v['id'])->update(['wdm'=>$vv[1]]);
                    if($er){
                        dump($v['id']);
                    }
                }
            }

        }
    }
    /**
     * 导出指定的所有数据批次Spreadsheet
     * @return void
     */
    public function downloadXlsx(){
        // 获取数据

        $this->uploadXlsx();
        exit();
        $getdata = input('get.');
        $data = Db::name('traceability')
//            ->where('company_id',null)
//            ->where('batch_id',null)
//            ->where('product_id',null)
            ->select()->toArray();
        $info = Db::view($this->dbname,'*')
            ->where('traceability.company_id',$getdata['company_id'])
            ->where('traceability.batch_id',$getdata['batch_id'])
            ->where('traceability.product_id',$getdata['product_id'])
            ->view('product', 'name as product_name', 'product.id = traceability.product_id', 'LEFT')
            ->view('company', 'name as company_name', 'company.id = traceability.company_id', 'LEFT')
            ->view('batch', 'code as batch_code', 'batch.id = traceability.batch_id', 'LEFT')
            ->find();
        $exl_name = $info['company_name'].'-'.$info['product_name'].'-'.$info['batch_code'];

        // 创建一份新的Excel文件
        $spreadsheet = new Spreadsheet();

        // 设置工作表名
        $spreadsheet->getActiveSheet()->setTitle('数据表格');
        // 将数据写入工作表中

        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle($info['batch_code'].'-二维码');
        $sheet->getColumnDimension('A')->setAutoSize(true);
        $sheet->getDefaultRowDimension()->setRowHeight(20);
        // 居中对齐
        $styleArray = [
            'alignment' => [
//                'horizontal' => Alignment::HORIZONTAL_CENTER, //水平居中
                'vertical' => Alignment::VERTICAL_CENTER, //垂直居中
            ],
        ];
        $sheet->getStyle('A')->applyFromArray($styleArray);
        $sheet->setCellValue('A1', '二维码URL')->getStyle('A1')->getFont()->setBold(true)->setName('黑体')->setSize(14);
        foreach ($data as $key => $item) {
            $num = $key + 2;
            $sheet->setCellValue(
                'A' . $num,
                $item['url'].'?c='.openssl_encrypt($item['code'], 'DES-ECB', config('app')['cache_shaf'], 0))
                ->getStyle('A' . $num)
                ->getFont()
//                ->setName('黑体')
                ->setSize(12);
        }
//        $spreadsheet->getActiveSheet()
//            ->fromArray($data, null, 'A1');
        // 保存Excel文件file
        $writer = new Xlsx($spreadsheet);
//        $writer->getFillHashTable();
//        exit();
        $fileName = $exl_name.'.xlsx';
        header("Content-Type:application/force-download");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition: attachment; filename="' . $fileName . '"');

        header("Content-Transfer-Encoding:binary");
        header("Last-Modified: " .gmdate("D, d M Y H:i:s") . "GMT");
        header("Cache-Control:must-revalidate, post-check=0,pre-check=0");
        header("Pragma:no-cache");
        $writer->save('php://output');

//        return re_success('成功',$writer->save('php://output'));
    }



    /**
     * 修改
     * @return false|string|void
     */
    public function update()
    {
        $data = input('put.');
        //模型验证
        $data['user_id'] = $this->getThisUser()['uid'];
        $model = new \app\api\model\Traceability();
        $er = $model->edit_vali($data);
        if($er){
            return  $er;
        }
        return $model->edit($data);

    }

    /**查询采用视图查询
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info()
    {
        $info = Db::name($this->dbname)
            ->find(input('get.id'));
        if($info){
            return re_success('获取成功',$info);
        }else{
            return re_error('获取失败');
        }
    }


    /**
     * 删除
     * @return false|string|void
     */
    public function dele()
    {
        $data = input('delete.');
        $model = new \app\api\model\Traceability();
        $er = $model->dele_vali($data);
        if($er){
            return  $er;
        }

        return $model->dele($data);
    }


    /**
     * 修改
     * @return false|string|void
     */
    public function updateStatus()
    {
        $data = input('put.');
        //模型验证
        $model = new \app\api\model\Traceability();
        $er = $model->edit_status_vali($data);
        if($er){
            return  $er;
        }
        return $model->editStatus($data);

    }
}
